#!/bin/bash

FEATURES=""
EXAMPLES=""
PLATFORM="x86"
VERBOSE=""
OTHERS=""
CMD="xbuild"
function usage()
{
    echo -e "-------------------------------------------------"
    echo -e "usage: $0 [-e] [-f feature] [-p platform] [CMD]"
    echo -e "    CMD: build | xbuild | clean"
    echo -e "    -p platform: x86 | ax | rk | tm | jz"
    echo -e "    -f feature: f-qbus | f-api | f-p2p"
    echo -e "    -e build examples"
    echo -e "-------------------------------------------------"
}

function print_args() {
  echo -e "CMD         : $CMD"
  echo -e "PLATFORM    : $PLATFORM"
  echo -e "FEATURES    : $FEATURES"
  echo -e "EXAMPLES    : $EXAMPLES"
  echo -e "VERBOSE     : $VERBOSE"
#  echo -e "OTHERS      : $OTHERS"
}

while getopts ef:p:hv OPT
do
  case $OPT in
    e) EXAMPLES="--examples";;
    f) if [ -n "$FEATURES" ]; then
        FEATURES="$FEATURES,$OPTARG"
      else
        FEATURES="$OPTARG"
      fi
      ;;
    p) PLATFORM="$OPTARG";;
    v) VERBOSE="-vvv";;
    h) usage
       exit 2;;
  esac
done
shift $((OPTIND -1))

OTHERS="$@"
if [ -n "$OTHERS" ]; then
  CMD="$@"
fi

if [ -n "$FEATURES" ]; then
  FEATURES="--features $FEATURES"
fi

print_args

case "$PLATFORM" in
  ax)
    . ~/bin/ax.sh
    export LIBCURL_LIB_DIR=~/projects/embed/IOT-AU38-01/app/opal_app/app/src/tutk_lib
    export OPENSSL_DIR=~/projects/embed/IOT-AU38-01/third_sdk/openssl
    TARGET="armv7-unknown-linux-gnueabihf"
    ;;
  tm)
    . ~/bin/tm.sh
    export LIBCURL_LIB_DIR=/home/armers/projects/webrtc/amazon-kinesis-dev-20221130/install.tm/lib
    export OPENSSL_DIR=/home/armers/projects/webrtc/amazon-kinesis-dev-20221130/install.tm
    TARGET="armv7-unknown-linux-gnueabihf"
    ;;
  rk)
    . ~/bin/rk.sh
    export LIBCURL_LIB_DIR=/home/armers/projects/webrtc/amazon-kinesis-dev-20221130/install.rk/lib
    export OPENSSL_DIR=/home/armers/projects/webrtc/amazon-kinesis-dev-20221130/install.rk
    export CC="arm-rockchip830-linux-uclibcgnueabihf-gcc"
    TARGET="armv7-unknown-linux-uclibceabihf"
    ;;
  jz)
    . ~/bin/t31.sh
    export LIBCURL_LIB_DIR=~/projects/embed/t31/ipc_sdk/lib
    export OPENSSL_INCLUDE_DIR=~/projects/embed/t31/ipc_sdk/include
    export OPENSSL_LIB_DIR=~/projects/embed/t31/ipc_sdk/lib
    TARGET="mipsel-unknown-linux-uclibc"
    ;;
  x86)
  	TARGET="x86_64-unknown-linux-gnu"
    ;;
  *)
    usage
    exit 1
esac

if [ "$CMD" == "xbuild" ] || [ "$CMD" == "build" ]; then
  cargo xbuild --release -Z build-std=std,panic_abort -Z build-std-features=panic_immediate_abort --target $TARGET $FEATURES $EXAMPLES $VERBOSE
elif [ "$CMD" == "clean" ]; then
  cargo clean
else
  echo "unknown cmd: $CMD"
fi
